from typing import List


class Solution:
    def __init__(self):
        self.cache = set()
        self.height = 0
        self.width = 0

    def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
        self.height = len(board)
        self.width = len(board[0])

        [y, x] = click
        if board[y][x] == 'M':
            board[y][x] = 'X'
        else:
            self.open(board, click)
        return board

    def open(self, board: List[List[str]], point: List[int]):
        [y, x] = point
        if (y, x) in self.cache:
            return
        self.cache.add((y, x))

        print("open {0},{1}".format(y, x))
        if y < 0 or y >= self.height:
            return
        if x < 0 or x >= self.width:
            return

        c = board[y][x]
        if c == 'E':
            count = self.countMines(board, point)
            if count == 0:
                board[y][x] = 'B'
                self.openBorder(board, point)
            else:
                board[y][x] = str(count)

    def openBorder(self, board: List[List[str]], point: List[int]):
        [y, x] = point
        self.open(board, [y - 1, x - 1])
        self.open(board, [y - 1, x])
        self.open(board, [y - 1, x + 1])
        self.open(board, [y, x - 1])
        self.open(board, [y, x + 1])
        self.open(board, [y + 1, x - 1])
        self.open(board, [y + 1, x])
        self.open(board, [y + 1, x + 1])

    def countMines(self,  board: List[List[str]], point: List[int]):
        [y, x] = point
        possiblePoints = [(y - 1, x - 1), (y - 1, x), (y - 1, x + 1), (y, x - 1),
                          (y, x + 1), (y + 1, x - 1), (y + 1, x), (y + 1, x + 1)]
        return len([(y, x) for (y, x) in possiblePoints if y >=
                    0 and y < self.height and x >= 0 and x < self.width and board[y][x] == 'M'])


solu = Solution()
board = [["E", "E", "E", "E", "E"],
         ["E", "E", "M", "E", "E"],
         ["E", "E", "E", "E", "E"],
         ["E", "E", "E", "E", "E"]]
for row in board:
    print(row)
nb = solu.updateBoard(board, [3, 0])
print("------------")
for row in nb:
    print(row)
